/**
 * Created by Dalyn on 2017/3/21.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import { Table, Icon, message } from 'antd';
import { Modal,Button } from 'fly';
import "./css/taxRefundManagement.css";
import Pagination from "./Pagination";
import Util from "../../util/Util";
import TaxRefundManagementMutation from './mutation/TaxRefundManagementMutation'
import OrderTaxRebateCompleteMutation from './mutation/OrderTaxRebateCompleteMutation'
import Config from "../../util/Config"
/*导出组件*/
export default class TaxRefundManagement extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            hadTax: false, //待退税  true为已退税
            rebateStatus: 1,
            searchInput:'',
            dataSource:[],
            pageSize: 10,
            totalResult: 0,
            pageNum: 1,
            visible: false,
            orderId: '',
            hightLight: false,
        };
        // this.selectClick = this.selectClick.bind(this);
        this.enterpriseId = sessionStorage.getItem('enterpriseId')
        this.uid = sessionStorage.getItem('uid')
        this.username = sessionStorage.getItem('username')
        this.url = Config.qiuniu
    }

    componentWillMount() {
      this.TaxRefundList()
    }

    TaxRefundList() {
      Relay.Store.commitUpdate(
          new TaxRefundManagementMutation({
            enid: this.enterpriseId,
            orderId: this.state.searchInput,
            rebateStatus: this.state.rebateStatus,
            sendStatus: '',
            pageSize: this.state.pageSize,
            pageNum: this.state.pageNum
          }),
          {
              onFailure: () => {
                  message.error("请求失败")
              },
              onSuccess: (response) => {
                  let data = response.enterpriseTaxRebateList.enterpriseTaxRebateList;
                  if (data.errorCode === "0") {
                    this.setState({
                      dataSource: data.enterpriseTaxRebateDomainList,
                      totalResult: data.totalResult
                    })
                  } else {
                      message.info(data.value)
                  }
              }

          }
      );
    }

    selectClick(type) {
      if (this.state.hadTax) {
        this.refs.pagination.setState({
            text:1,
        })
        this.setState({
          hadTax: !this.state.hadTax,
          rebateStatus: 1,
          searchInput: '',
          pageNum: 1
        },()=>{
          this.TaxRefundList()
        })
      } else {
        this.refs.pagination.setState({
            text:1,
        })
        this.setState({
          hadTax: !this.state.hadTax,
          rebateStatus: 2,
          searchInput: '',
          pageNum: 1
        },()=>{
          this.TaxRefundList()
        })
      }

    }

    changeInput(e) {
      this.setState({
        searchInput: e.target.value
      })
    }
    focus() {
        this.setState({
            highLight: true
        })
    }
    blur(){
        this.setState({
            highLight: false
        })
    }
    searchClick() {
      this.TaxRefundList()
    }
    updateTaxStatus(orderId) {
      Relay.Store.commitUpdate(
          new OrderTaxRebateCompleteMutation({
            rebateUser: this.uid,
            orderId: this.state.orderId,
            rebateUserName: this.username,
          }),
          {
              onFailure: () => {
                  message.error("请求失败")
              },
              onSuccess: (response) => {
                  let data = response.orderTaxRebateComplete.orderTaxRebateComplete;
                  if (data.errorCode === "0") {
                      message.info('完成退税成功')
                      this.TaxRefundList()
                  } else {
                      message.info(data.value)
                  }
              }

          }
      );
    }

    showModal = (orderId) => {
        this.setState({
          visible: true,
          orderId: orderId
        });
    }
    handleOk = (e) => {
      this.updateTaxStatus()
      this.setState({
        visible: false,
      });
    }
    handleCancel = (e) => {
      console.log(e);
      this.setState({
        visible: false,
      });
    }

    /*页码*/
    onSure(size, num) {
        this.setState({
            pageSize: size,
            pageNum: num,
            loading:true,
        }, ()=>{
          this.TaxRefundList()
        })
    }

    enterOrderDetail(record) {
        record.oid = record.orderId
        hashHistory.push({pathname:'/OrderIndex/',state:{defaultActiveKey: 1,'record':record}});
          // if (record.orderType == 1) {
          //   hashHistory.push("/orderdetailgms/" + record.orderId)
          // } else if (record.orderType == 2) {
          //   hashHistory.push("/orderdetailraw/" + record.orderId)
          // } else if (record.orderType == 3) {
          //   hashHistory.push("/orderdetailcloth/" + record.orderId)
          // } else if (record.orderType == 4) {
          //   hashHistory.push("/orderdetailprint/" + record.orderId)
          // } else if (record.orderType == 5) {
          //   hashHistory.push("/orderdetailyarn/" + record.orderId)
          // }
    }
    invoiceDownload(invoiceFileJson) {

      // if (invoiceFileJson) {
      //   JSON.parse(invoiceFileJson).map((v, item) =>{
      //     v.response ? (
      //       window.open(this.url + v.response.key + `?attname=${v.name}`)
      //     ) : null
      //   })
      // }
      Array.isArray(JSON.parse(invoiceFileJson)) &&   JSON.parse(invoiceFileJson).forEach((i,k)=>{
       const h = this.url + i.response.key + `?attname=`+ i.name, a = document.createElement("a");
       a.href = h;
       a.setAttribute("download","");
       a.click();
     });
    }
    render(){
      const columns = [{
        title: '订单编号',
        dataIndex: 'orderId',
        key: 'orderId',
        render: (text, record) => (<a className="tax_color" onClick={this.enterOrderDetail.bind(this, record)}>{text}</a>),
      }, {
        title: '合同号',
        dataIndex: 'contract',
        key: 'contract',
      }, {
        title: '客户',
        dataIndex: 'traderName',
        key: 'traderName',
      }, {
        title: '订单金额',
        dataIndex: 'orderAmount',
        key: 'orderAmount',
        render: (text, record) => {
            return (
                <span>{Util.doubleFormat(record.orderAmount)}</span>
            )
        }
      }, {
        title: '发票金额',
        dataIndex: 'invoiceMoney',
        key: 'invoiceMoney',
        render: (text, record) => {
            return (
                <span>{Util.doubleFormat(record.invoiceMoney)}</span>
            )
        }
      }, {
        title: '退税金额',
        dataIndex: 'rebateMoney',
        key: 'rebateMoney',
        render: (text, record) => {
            return (
                <span>{Util.doubleFormat(record.rebateMoney)}</span>
            )
        }
      }, {
        title: '发票张数',
        dataIndex: 'invoiceNum',
        key: 'invoiceNum',
        render: (text, record) => {
            return (
                <span>{Util.doubleFormat(record.invoiceNum)}</span>
            )
        }
      }, {
        title: '快递信息',
        dataIndex: 'expressName',
        key: 'expressName',
        render: (text, record) => {
          return (
            <p style={{maxWidth: '170px', margin: '0 auto'}}><span title={record.expressName} style={{display:'block'}}>{record.expressName}</span><span title={record.expressSheet}>{record.expressSheet}</span></p>
          )
        }
      }, {
        title: '状态',
        dataIndex: 'address',
        key: 'address',
        render: (text, record) => {
            return record.rebateStatus == 1 ? '待退税' : '已退税'
        }
      }, {
        title: '操作人',
        dataIndex: 'rebateUserName',
        key: 'rebateUserName',
      },{
        title: '操作',
        key: 'action',
        render: (text, record) => {
          if (record.rebateStatus == 1 ) {
            return (<p>
                <a className="tax_color" onClick={this.showModal.bind(this, record.orderId)}>完成退税</a>&nbsp;
                <a className="tax_color" onClick={this.invoiceDownload.bind(this, record.invoiceFileJson)}>发票下载</a>
              </p>)
          } else {
            return (<a className="tax_color" onClick={this.invoiceDownload.bind(this, record.invoiceFileJson)}>
              发票下载
            </a>)
          }
        }

      }];
        const { hadTax, searchInput } = this.state
        return (
          <div className="tax_box">
            <p className='tax_select'>
                <span onClick={this.selectClick.bind(this,1)} className={!hadTax ? "tax_select_span active" : "tax_select_span"}>待退税</span>
                <span onClick={this.selectClick.bind(this,2)} className={hadTax ? "tax_select_span active" : "tax_select_span"}>已退税</span>
            </p>
            <div className="tax_search_box">
                <input
                    className="tax_search_box_input"
                    value={searchInput}
                    onChange={this.changeInput.bind(this)}
                    placeholder='请输入订单编号'
                    style={this.state.highLight ? {'border':'1px solid #36b3b3'} : null}
                    onFocus={this.focus.bind(this)}
                    onBlur={this.blur.bind(this)}
                />
                <Button className="tax_search_box_btn" onClick={this.searchClick.bind(this)}>搜索</Button>
            </div>
            <Table
              className="order_table"
              columns={columns}
              dataSource={this.state.dataSource}
              pagination={false}
              // bordered
            />
            <Modal
              title="提示"
              visible={this.state.visible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
              wrapClassName="taxRefundManagementModal"
            >
              <p style={{display:'flex',alignItems:'center',fontSize:'16px'}}>
                  <i style={{width:'34px',marginRight:'10px',height:'34px',display:'inlineBlock',fontSize:'24px',borderRadius:'50%',textAlign:'center',lineHeight:'34px',background:'#ffbf00',color:'#fff'}}>i</i>
                  确认要将该订单标记为已退税状态吗？
              </p>
            </Modal>
            <div style={{marginRight:'20px'}}>
              <Pagination eachSize={this.state.pageSize} dataSize={this.state.totalResult} onSure={this.onSure.bind(this)} ref={'pagination'}/>
            </div>
          </div>
        )
    }
}
